﻿using Engine;
using Engine.Graphics;
using IDManager;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using TemplatesDatabase;

namespace Game
{
    public class BlockIDScreen : Screen
    {
        public ListPanelWidget list;

        public Screen m_previousScreen;

        public TextBoxWidget key;

        public LabelWidget textboxText;

        public BevelledButtonWidget searchButton;

        public BlockIconWidget iconWidget;

        public CanvasWidget infoPanel;

        public ListPanelWidget occuList;

        public ButtonWidget pickButton;

        public ButtonWidget quesButton;

        private IDPickType type = IDPickType.None;

        public Dictionary<string, string> helps = new Dictionary<string, string>
        {
            {"ID条目的颜色是什么意思", "绿色: 占用这个ID的方块只有一个，不会报错\n黄色: 原版方块使用的ID被Mod方块占用，可能为重写原版方块，一般情况不会报错\n红色: 这个ID被多个Mod方块占用，大概率会报错" },
            {"为什么搜索框与搜索按钮没对齐", "SC特性，写死在源码里的，很难改" },
            {"中括号里的数字是什么意思", "表示占用那个ID的方块数量" }
        };

        private string questionText;

        public IDPickType IDPickType
        {
            get { return type; }
            set
            {
                type = value;
                SetPickButtonText();
                AddItems(key.Text);
            }
        }
        public BlockIDScreen()
        {
            XElement node = ContentManager.Get<XElement>("Add/BlockIDScreen");
            LoadContents(this, node);
            list = Children.Find<ListPanelWidget>("List");
            key = Children.Find<TextBoxWidget>("Key");
            textboxText = Children.Find<LabelWidget>("TextboxText");
            searchButton = Children.Find<BevelledButtonWidget>("SearchButton");
            iconWidget = Children.Find<BlockIconWidget>("SelectedIcon");
            infoPanel = Children.Find<CanvasWidget>("InfoPanel");
            occuList = Children.Find<ListPanelWidget>("OccuList");
            pickButton = Children.Find<ButtonWidget>("Pick");
            quesButton = Children.Find<ButtonWidget>("Question");
            list.ItemSize = 30;
            occuList.ItemSize = 40;
            infoPanel.IsVisible = false;

            list.ItemWidgetFactory = delegate (object item)
            {
                int id = (int)item;
                XElement node2 = ContentManager.Get<XElement>("Add/BlockIDItem");
                var obj = (ContainerWidget)LoadWidget(this, node2, null);
                LabelWidget idWidget = obj.Children.Find<LabelWidget>("Index");
                LabelWidget nameWidget = obj.Children.Find<LabelWidget>("ClassNames");
                LabelWidget numWidget = obj.Children.Find<LabelWidget>("Nums");

                idWidget.Text = id.ToString();
                //id处理
                List<IDInfo> use = BlockIDManager.FindUseNames(id);
                string s = "";
                for (int i = 0; i < use.Count; i++)
                {
                    if (i > 0) s += " | ";
                    s += use[i].AssemblyFirstName;
                }
                nameWidget.Text = s;
                numWidget.Text = "[" + use.Count.ToString() + "]";
                numWidget.Margin = new Vector2(obj.Children.Find<LabelWidget>("Index").Size.X - obj.Children.Find<LabelWidget>("ClassNames").Size.X + 500, 0);

                //上色标重
                switch (use.Count)
                {
                    case 0:
                        nameWidget.Color = Color.White; break;
                    case 1:
                        nameWidget.Color = Color.Green; break;
                    case int i when i >= 2:
                        nameWidget.Color = use[0].AssemblyName == typeof(AirBlock).Assembly.FullName ? Color.Yellow : Color.Red; break;
                }

                return obj;
            };
            list.ItemClicked += delegate (object item)
            {
                int id = (int)item;
                ShowInfo(id);
            };
            occuList.ItemWidgetFactory = (object info) =>
            {
                IDInfo idInfo = (IDInfo)info;
                XElement node2 = ContentManager.Get<XElement>("Add/OccuIDItem");
                var obj = (ContainerWidget)LoadWidget(this, node2, null);
                LabelWidget assemblyWidget = obj.Children.Find<LabelWidget>("AssemblyName");
                LabelWidget nameWidget = obj.Children.Find<LabelWidget>("ClassName");
                nameWidget.Text = idInfo.ClassName;
                assemblyWidget.Text = idInfo.AssemblyFirstName;
                return obj;
            };
            occuList.ItemClicked += (object info) =>
            {
                if (occuList.SelectedItem == info && info is IDInfo)
                {
                    IDInfo info1 = (IDInfo)info;
                    DialogsManager.ShowDialog(this, new MessageDialog($"{info1.ClassName}详细信息", $"类名:{info1.ClassName}\r\n程序集:{info1.AssemblyName}", "关闭", null, null));
                }
            };

            for (int i = 0; i < 1024; i++)
            {
                list.AddItem(i);
            }
            //pickButton.IsEnabled = false;

            //加载帮助文本
            foreach (KeyValuePair<string, string> ques in helps)
            {
                questionText += "Q:" + ques.Key;
                questionText += Environment.NewLine;
                questionText += "A:" + ques.Value;
                questionText += Environment.NewLine + Environment.NewLine;
            }

            SetPickButtonText();
        }

        public override void Update()
        {
            base.Update();
            if (Input.Back || Input.Cancel || Children.Find<ButtonWidget>("TopBar.Back").IsClicked)
            {
                ScreensManager.SwitchScreen(ScreensManager.PreviousScreen);
            }
            textboxText.Text = key.Text.Length > 0 ? "" : "搜索包含指定数字的ID";
            //搜索功能
            if (searchButton.IsClicked)
            {
                AddItems(key.Text);
            }

            if (pickButton.IsClicked)
            {
                List<string> types = TypeToString();

                DialogsManager.ShowDialog(this, new ListSelectionDialog("选择筛选", types, 56, (object item) => (string)item, (object item2) => { SetPickType((string)item2); }));
            }

            if (quesButton.IsClicked)
            {
                DialogsManager.ShowDialog(this, new MessageDialog("Q&A", questionText, "关闭", null, null));
            }
        }

        private void ShowInfo(int id)
        {
            try
            {
                infoPanel.IsVisible = true;
                iconWidget.Contents = id;
                Block selectedB = BlocksManager.Blocks[id];
                FindLabel("B.ClassName").Text = $"类名: {selectedB.GetType().Name}";
                FindLabel("B.Name").Text = $"名称: {selectedB.GetDisplayName(null, id)}";
                occuList.ClearItems();
                List<IDInfo> infos = BlockIDManager.FindUseNames(id);
                foreach (IDInfo info in infos)
                {
                    occuList.AddItem(info);
                }
            }
            catch (Exception ex)
            {
                DialogsManager.ShowDialog(this, new MessageDialog("出错了", ex.ToString(), "确定", null, null));
            }
        }

        private LabelWidget FindLabel(string name)
        {
            return Children.Find<LabelWidget>(name);
        }

        private void SetPickButtonText()
        {
            switch (type)
            {
                case IDPickType.None:
                    pickButton.Text = "筛选: 无"; break;
                case IDPickType.Warring:
                    pickButton.Text = "筛选: 重复占用(非原版)"; break;
                case IDPickType.Error:
                    pickButton.Text = "筛选: 重复占用(非原版)"; break;
                case IDPickType.NoEmpty:
                    pickButton.Text = "筛选: 全部占用"; break;
            }
        }
        private List<string> TypeToString()
        {
            List<string> enumList = new List<string>();

            foreach (IDPickType value in Enum.GetValues(typeof(IDPickType)))
            {
                string text = string.Empty;

                switch (value)
                {
                    case IDPickType.None:
                        text = "无";
                        break;
                    /*
                case IDPickType.Warring:
                    text = "重复占用(非原版)";
                    break;
                case IDPickType.Error:
                    text = "重复占用(非原版)";
                    break;*/
                    case IDPickType.NoEmpty:
                        text = "全部占用";
                        break;
                }

                if (text.Length > 0) enumList.Add(text);
            }
            return enumList;
        }

        private void SetPickType(string str)
        {
            switch (str)
            {
                case "无":
                    IDPickType = IDPickType.None; break;
                case "重复占用(原版)":
                    IDPickType = IDPickType.Warring; break;
                case "重复占用(非原版)":
                    IDPickType = IDPickType.Error; break;
                case "全部占用":
                    IDPickType = IDPickType.NoEmpty; break;
                default:
                    throw new ArgumentException("Invalid enum string");
            }
        }

        private void AddItems(string keyID)
        {
            list.ClearItems();
            if (keyID.Length > 0 && int.TryParse(key.Text, out int keyID2))
            {
                for (int i = 0; i < 1024; i++)
                {
                    if (i.ToString().Contains(keyID))
                    {
                        List<IDInfo> ids = BlockIDManager.FindUseNames(i);
                        if (IDPickType == IDPickType.None) list.AddItem(i);
                        else if (IDPickType == IDPickType.NoEmpty && ids.Count >= 1) list.AddItem(i);
                    }
                }
            }
            else
            {
                for (int i = 0; i < 1024; i++)
                {
                    List<IDInfo> ids = BlockIDManager.FindUseNames(i);
                    if (IDPickType == IDPickType.None) list.AddItem(i);
                    else if (IDPickType == IDPickType.NoEmpty && ids.Count >= 1) list.AddItem(i);
                }
                key.Text = "";
            }
        }
    }
}
